import { x as useMainStore, V as getStorageSync, _ as _export_sfc, m as mpMixin, a as mixin, c as createBlock, o as openBlock, E as setStorage, af as removeStorageSync, i as index$g, z as ref, A as computed, B as onLoad, U as onShow, ag as navigateBack, ah as reLaunch, w as withCtx, j as resolveEasycom, k as resolveDynamicComponent, b as createVNode, t as createTextVNode, ae as Input, Q as index$x, n as normalizeStyle, u as toDisplayString, ai as index$u, aj as index$t, s as index$i, a1 as navigateTo, ak as getCurrentPages$1 } from './index-Cc4oxzDN.js';
import { b as __easycom_5 } from './uv-toast.nS_Liirv.js';
import { _ as __easycom_3 } from './layout.FALqt04o.js';
import { s as smsSend, a as userLogin } from './auth.CJjHezpF.js';
import { e as ensurePlatformId } from './platformId.BGlVpsd7.js';
import { g as getCurrentPlatform } from './platform.EIa5ETLd.js';
import './uv-loading-icon.DuNkB54M.js';

/**
 * 获取当前的 openid
 * @returns {string} 当前的 openid
 */
function getCurrentOpenid() {
    const main = useMainStore();
    return main.GET_OPENID();
}

/**
 * 检查当前是否有有效的 openid
 * @returns {boolean} 是否有有效的 openid
 */
function hasValidOpenid() {
    const openid = getCurrentOpenid();
    return !!(openid && openid.length > 0);
}

/**
 * 获取用于登录接口的 openid 参数
 * 如果没有 openid，返回空字符串而不是 null
 * @returns {string} 用于登录接口的 openid
 */
function getLoginOpenid() {
    const openid = getCurrentOpenid();
    return openid || '';
}

/**
 * 调试信息：打印当前 openid 状态
 */
function debugOpenidInfo() {
    const openid = getCurrentOpenid();
    const buyerId = getStorageSync('buyer_id');
    const storedOpenid = getStorageSync('openid');

    console.log('=== OpenID 状态调试信息 ===');
    console.log('当前 openid (store):', openid);
    console.log('buyer_id (storage):', buyerId);
    console.log('openid (storage):', storedOpenid);
    console.log('是否有效:', hasValidOpenid());
    console.log('=========================');

    return {
        currentOpenid: openid,
        buyerId: buyerId,
        storedOpenid: storedOpenid,
        isValid: hasValidOpenid()
    };
}

const props = {
	props: {
		// 倒计时总秒数
		seconds: {
			type: [String, Number],
			default: 60
		},
		// 尚未开始时提示
		startText: {
			type: String,
			default: '获取验证码'
		},
		// 正在倒计时中的提示
		changeText: {
			type: String,
			default: 'X秒重新获取'
		},
		// 倒计时结束时的提示
		endText: {
			type: String,
			default: '重新获取'
		},
		// 是否在H5刷新或各端返回再进入时继续倒计时
		keepRunning: {
			type: Boolean,
			default: false
		},
		// 为了区分多个页面，或者一个页面多个倒计时组件本地存储的继续倒计时变了
		uniqueKey: {
			type: String,
			default: ''
		},
		...uni.$uv?.props?.code
	}
};

/**
	 * Code 验证码倒计时
	 * @description 考虑到用户实际发送验证码的场景，可能是一个按钮，也可能是一段文字，提示语各有不同，所以本组件不提供界面显示，只提供倒计时文本，由用户将文本嵌入到具体的场景
	 * @tutorial https://www.uvui.cn/components/code.html
	 * @property {String | Number}	seconds			倒计时所需的秒数（默认 60 ）
	 * @property {String}			startText		开始前的提示语，见官网说明（默认 '获取验证码' ）
	 * @property {String}			changeText		倒计时期间的提示语，必须带有字母"x"，见官网说明（默认 'X秒重新获取' ）
	 * @property {String}			endText			倒计结束的提示语，见官网说明（默认 '重新获取' ）
	 * @property {Boolean}			keepRunning		是否在H5刷新或各端返回再进入时继续倒计时（ 默认false ）
	 * @property {String}			uniqueKey		为了区分多个页面，或者一个页面多个倒计时组件本地存储的继续倒计时变了
	 *
	 * @event {Function}	change	倒计时期间，每秒触发一次
	 * @event {Function}	start	开始倒计时触发
	 * @event {Function}	end		结束倒计时触发
	 * @example <uv-code ref="uCode" @change="codeChange" seconds="20"></uv-code>
	 */
	const _sfc_main$1 = {
		name: "uv-code",
		mixins: [mpMixin, mixin, props],
		data() {
			return {
				secNum: this.seconds,
				timer: null,
				canGetCode: true, // 是否可以执行验证码操作
			}
		},
		mounted() {
			this.checkKeepRunning();
		},
		watch: {
			seconds: {
				immediate: true,
				handler(n) {
					this.secNum = n;
				}
			}
		},
		methods: {
			checkKeepRunning() {
				// 获取上一次退出页面(H5还包括刷新)时的时间戳，如果没有上次的保存，此值可能为空
				let lastTimestamp = Number(getStorageSync(this.uniqueKey + '_$uCountDownTimestamp'));
				if (!lastTimestamp) return this.changeEvent(this.startText)
				// 当前秒的时间戳
				let nowTimestamp = Math.floor((+new Date()) / 1000);
				// 判断当前的时间戳，是否小于上一次的本该按设定结束，却提前结束的时间戳
				if (this.keepRunning && lastTimestamp && lastTimestamp > nowTimestamp) {
					// 剩余尚未执行完的倒计秒数
					this.secNum = lastTimestamp - nowTimestamp;
					// 清除本地保存的变量
					removeStorageSync(this.uniqueKey + '_$uCountDownTimestamp');
					// 开始倒计时
					this.start();
				} else {
					// 如果不存在需要继续上一次的倒计时，执行正常的逻辑
					this.changeEvent(this.startText);
				}
			},
			// 开始倒计时
			start() {
				// 防止快速点击获取验证码的按钮而导致内部产生多个定时器导致混乱
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
				this.$emit('start');
				this.canGetCode = false;
				// 这里放这句，是为了一开始时就提示，否则要等setInterval的1秒后才会有提示
				this.changeEvent(this.changeText.replace(/x|X/, this.secNum));
				this.timer = setInterval(() => {
					if (--this.secNum) {
						// 用当前倒计时的秒数替换提示字符串中的"x"字母
						this.changeEvent(this.changeText.replace(/x|X/, this.secNum));
					} else {
						clearInterval(this.timer);
						this.timer = null;
						this.changeEvent(this.endText);
						this.secNum = this.seconds;
						this.$emit('end');
						this.canGetCode = true;
					}
				}, 1000);
				this.setTimeToStorage();
			},
			// 重置，可以让用户再次获取验证码
			reset() {
				this.canGetCode = true;
				clearInterval(this.timer);
				this.secNum = this.seconds;
				this.changeEvent(this.endText);
			},
			changeEvent(text) {
				this.$emit('change', text);
			},
			// 保存时间戳，为了防止倒计时尚未结束，H5刷新或者各端的右上角返回上一页再进来
			setTimeToStorage() {
				if (!this.keepRunning || !this.timer) return
				// 记录当前的时间戳，为了下次进入页面，如果还在倒计时内的话，继续倒计时
				// 倒计时尚未结束，结果大于0；倒计时已经开始，就会小于初始值，如果等于初始值，说明没有开始倒计时，无需处理
				if (this.secNum > 0 && this.secNum <= this.seconds) {
					// 获取当前时间戳(+ new Date()为特殊写法)，除以1000变成秒，再去除小数部分
					let nowTimestamp = Math.floor((+new Date()) / 1000);
					// 将本该结束时候的时间戳保存起来 => 当前时间戳 + 剩余的秒数
					setStorage({
						key: this.uniqueKey + '_$uCountDownTimestamp',
						data: nowTimestamp + Number(this.secNum)
					});
				}
			}
		},









		// 组件销毁，兼容vue3
		unmounted() {
			this.setTimeToStorage();
			clearTimeout(this.timer);
			this.timer = null;
		}

	};

function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_v_uni_view = index$g;

  return (openBlock(), createBlock(_component_v_uni_view, { class: "uv-code" }))
}
const __easycom_2 = /*#__PURE__*/_export_sfc(_sfc_main$1, [['render',_sfc_render]]);

/**
 * 测试工具函数
 */

/**
 * 验证手机号格式
 * @param {string} mobile 手机号
 * @returns {boolean} 是否为有效手机号
 */
const mobile = (mobile) => {
    const reg = /^1[3-9]\d{9}$/;
    return reg.test(mobile);
};

const _sfc_main = {
  __name: 'login',
  setup(__props) {

	const main = useMainStore();
	ref('登录');
	const mobile$1 = ref('');
	const captcha = ref('');
	const captchaText = ref('获取验证码');
	ref('');
	const seconds = ref(60);
	const isChecked = ref(false);
	const openid = ref('');
	const uToast = ref();
	const uCode = ref();

	const captchaStyle = computed(() => {
		let style = {};
		if (mobile$1.value && captchaText.value == '获取验证码') {
			style.color = "#fff";
			style.backgroundColor = '#f9ae3d';
		}
		return style;
	});

	// 初始化 openid
	const initOpenid = () => {
		// 使用工具函数获取 openid
		const storedOpenid = getCurrentOpenid();
		if (storedOpenid) {
			openid.value = storedOpenid;
			console.log('初始化 openid:', storedOpenid);
		} else {
			console.log('未找到已保存的 openid');
		}
		
		// 打印调试信息
		debugOpenidInfo();
	};

	onLoad((options) => {
		console.log('=== 登录页面 onLoad 触发 ===');
		console.log('页面参数:', options);
	});

	onShow(() => {
		console.log('=== 登录页面 onShow 触发 ===');

		// 初始化 openid
		initOpenid();

		// 检查用户是否已经登录，如果已登录则直接返回
		if (main.isLogin) {
			console.log('用户已登录，直接返回上一页');
			setTimeout(() => {
				navigateBack({
					fail: () => {
						// 如果无法返回，跳转到首页
						reLaunch({
							url: '/pages/index/index'
						});
					}
				});
			}, 500);
			return;
		}

		console.log('登录页面就绪，等待用户手动登录');
	});




	// 获取验证码
	const getCaptcha = async () => {
		if (mobile(mobile$1.value) == false) {
			uToast.value.show({
				message: '手机号码格式不对',
				type: 'error'
			});
			return
		}
		uCode.value.start();
		let data = await smsSend({
			mobile: mobile$1.value,
			scene: 1
		});
		if (data) {
			uToast.value.show({
				message: '验证码发送成功',
				type: 'success'
			});
		}
	};
	// 验证码开始
	const startCaptcha = () => {
		console.log('start');
	};
	// 验证码结束
	const endCaptcha = () => {
		console.log('end');
		captchaText.value = '获取验证码';
	};
	const changeCapcha = (text) => {
		console.log('change:' + text);
		captchaText.value = text;
	};
	// 提交
	const submit = () => {

		if (mobile(mobile$1.value) == false) {
			uToast.value.show({
				message: '手机号码格式不对',
				type: 'error'
			});
			return
		}

		if (!isChecked.value) {
			uToast.value.show({
				message: '请勾选下面协议',
				type: 'error'
			});
			return
		}

		login();

	};
	// 登录
	const login = async () => {
		console.log('=== 开始手机号验证码登录 ===');
		
		// 获取当前平台标识
		const currentPlatform = getCurrentPlatform();
		console.log('当前平台:', currentPlatform);
		
		// 使用工具函数获取 openid
		const currentOpenid = getLoginOpenid();
		console.log('当前 openid:', currentOpenid);
		
		// 根据平台设置 from 参数
		let from = 'h5'; // 默认值
		if (currentPlatform === 'alipay') {
			from = 'alipay';
		} else if (currentPlatform === 'wechat') {
			from = 'wechat';
		}
		
		// 构建登录参数 - 根据平台类型设置正确的字段名
		let loginParams = {
			mobile: mobile$1.value,
			code: captcha.value,
			from: from
		};
		
		// 根据平台类型设置正确的ID字段
		if (from === 'wechat' && currentOpenid) {
			loginParams.openid = currentOpenid;  // 微信平台使用 openid
		} else if (from === 'alipay' && currentOpenid) {
			loginParams.buyerId = currentOpenid; // 支付宝平台使用 buyerId
		}
		
		console.log('登录参数:', loginParams);
		
		let data = await userLogin(loginParams);
		
		if (data) {
			setStorage({
				key: 'userinfo',
				data: data.userInfo
			});
			setStorage({
				key: 'accessToken',
				data: data.accessToken
			});
			main.SET_MEMBER(data.userInfo);
			main.SET_TOKEN(data.accessToken);
			main.SET_ACCESSES(data.accesses);

			// 显示登录成功提示
			uToast.value.show({
				message: '登录成功',
				type: 'success'
			});

			// 登录成功后自动补充平台ID
			try {
				await ensurePlatformId('auto');
				console.log('平台ID补充完成');
			} catch (error) {
				console.log('平台ID补充失败，但不影响登录:', error);
			}

			setTimeout(function() {
				// 检查页面栈，如果是第一个页面则跳转到首页
				const pages = getCurrentPages$1();
				console.log('当前页面栈长度:', pages.length);
				
				if (pages.length <= 1) {
					// 如果是第一个页面，跳转到首页
					console.log('当前是第一个页面，跳转到首页');
					reLaunch({
						url: '/pages/index/index'
					});
				} else {
					// 有上一页，正常返回
					navigateBack({
						delta: 1,
						success: (res) => {
							console.log('返回上一页成功', res);
							// 刷新上一页
							const pages = getCurrentPages$1();
							if (pages.length > 1) {
								const prevPage = pages[pages.length - 2];
								if (prevPage && prevPage.onLoad) {
									prevPage.onLoad();
								}
							}
						},
						fail: (res) => {
							console.log('返回上一页失败', res);
							// 返回失败时也跳转到首页
							reLaunch({
								url: '/pages/index/index'
							});
						}
					});
				}
			}, 2000);
		}
	};

	const serv = (id, name) => {
		navigateTo({
			url: '/pages/components/pages/mine/content?id=' + id + '&name=' + name
		});
	};
	const onChange = (e) => {
		isChecked.value = e.detail.value.includes('agree');
	};


return (_ctx, _cache) => {
  const _component_v_uni_view = index$g;
  const _component_v_uni_input = Input;
  const _component_uv_code = resolveEasycom(resolveDynamicComponent("uv-code"), __easycom_2);
  const _component_v_uni_button = index$x;
  const _component_v_uni_checkbox = index$t;
  const _component_v_uni_checkbox_group = index$u;
  const _component_v_uni_text = index$i;
  const _component_uv_toast = resolveEasycom(resolveDynamicComponent("uv-toast"), __easycom_5);
  const _component_layout = resolveEasycom(resolveDynamicComponent("layout"), __easycom_3);

  return (openBlock(), createBlock(_component_layout, null, {
    default: withCtx(() => [
      createVNode(_component_v_uni_view, { class: "wrap" }, {
        default: withCtx(() => [
          createVNode(_component_v_uni_view, { class: "top" }),
          createVNode(_component_v_uni_view, { class: "content" }, {
            default: withCtx(() => [
              createVNode(_component_v_uni_view, { class: "title" }, {
                default: withCtx(() => [
                  createTextVNode("欢迎登录")
                ]),
                _: 1
              }),
              createVNode(_component_v_uni_input, {
                class: "u-border-bottom",
                type: "number",
                modelValue: mobile$1.value,
                "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => ((mobile$1).value = $event)),
                placeholder: "请输入手机号"
              }, null, 8, ["modelValue"]),
              createVNode(_component_v_uni_view, { class: "tips" }, {
                default: withCtx(() => [
                  createTextVNode("未注册的手机号验证后自动创建账号")
                ]),
                _: 1
              }),
              createVNode(_component_v_uni_view, { style: {"display":"flex"} }, {
                default: withCtx(() => [
                  createVNode(_component_v_uni_view, { style: {"width":"50%"} }, {
                    default: withCtx(() => [
                      createVNode(_component_v_uni_input, {
                        style: {"height":"100rpx"},
                        class: "u-border-bottom",
                        type: "number",
                        modelValue: captcha.value,
                        "onUpdate:modelValue": _cache[1] || (_cache[1] = $event => ((captcha).value = $event)),
                        placeholder: "请输入验证码"
                      }, null, 8, ["modelValue"])
                    ]),
                    _: 1
                  }),
                  createVNode(_component_v_uni_view, { style: {"width":"50%"} }, {
                    default: withCtx(() => [
                      createVNode(_component_v_uni_button, {
                        style: normalizeStyle([{"height":"100rpx"}, [captchaStyle.value]]),
                        onClick: getCaptcha,
                        class: "getCaptcha"
                      }, {
                        default: withCtx(() => [
                          createTextVNode(toDisplayString(captchaText.value) + " ", 1),
                          createVNode(_component_uv_code, {
                            seconds: seconds.value,
                            onEnd: endCaptcha,
                            onStart: startCaptcha,
                            ref_key: "uCode",
                            ref: uCode,
                            onChange: changeCapcha
                          }, null, 8, ["seconds"])
                        ]),
                        _: 1
                      }, 8, ["style"])
                    ]),
                    _: 1
                  })
                ]),
                _: 1
              }),
              createVNode(_component_v_uni_button, {
                onClick: submit,
                style: {"color":"#fff","background-color":"#f9ae3d"},
                type: "primary",
                class: "login"
              }, {
                default: withCtx(() => [
                  createTextVNode("登录 ")
                ]),
                _: 1
              })
            ]),
            _: 1
          }),
          createVNode(_component_v_uni_view, { class: "buttom" }, {
            default: withCtx(() => [
              createVNode(_component_v_uni_view, { class: "loginType" }),
              createVNode(_component_v_uni_view, {
                class: "hint",
                style: {"display":"flex","align-items":"center"}
              }, {
                default: withCtx(() => [
                  createVNode(_component_v_uni_checkbox_group, { onChange: onChange }, {
                    default: withCtx(() => [
                      createVNode(_component_v_uni_checkbox, {
                        value: "agree",
                        checked: isChecked.value
                      }, null, 8, ["checked"])
                    ]),
                    _: 1
                  }),
                  createVNode(_component_v_uni_text, { style: {"margin-left":"10rpx"} }, {
                    default: withCtx(() => [
                      createTextVNode("我已经阅读并遵守")
                    ]),
                    _: 1
                  }),
                  createVNode(_component_v_uni_text, {
                    class: "link",
                    onClick: _cache[2] || (_cache[2] = $event => (serv(29,'用户协议'))),
                    style: {"margin":"0 4rpx"}
                  }, {
                    default: withCtx(() => [
                      createTextVNode("《用户协议》")
                    ]),
                    _: 1
                  }),
                  createVNode(_component_v_uni_text, null, {
                    default: withCtx(() => [
                      createTextVNode("与")
                    ]),
                    _: 1
                  }),
                  createVNode(_component_v_uni_text, {
                    class: "link",
                    onClick: _cache[3] || (_cache[3] = $event => (serv(30,'隐私政策'))),
                    style: {"margin-left":"4rpx"}
                  }, {
                    default: withCtx(() => [
                      createTextVNode("《隐私政策》")
                    ]),
                    _: 1
                  })
                ]),
                _: 1
              })
            ]),
            _: 1
          }),
          createVNode(_component_uv_toast, {
            ref_key: "uToast",
            ref: uToast
          }, null, 512)
        ]),
        _: 1
      })
    ]),
    _: 1
  }))
}
}

};
const login = /*#__PURE__*/_export_sfc(_sfc_main, [['__scopeId',"data-v-cb09c082"]]);

export { login as default };
